'use strict';

module.exports = app => {
  const { STRING, INTEGER, TEXT, DATE, ENUM } = app.Sequelize;

  const Comment = app.model.define('comment', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    user_id: {
      type: INTEGER,
      allowNull: false,
      comment: '用户ID',
    },
    target_type: {
      type: ENUM('outfit', 'clothing'),
      allowNull: false,
      comment: '评论目标类型',
    },
    target_id: {
      type: INTEGER,
      allowNull: false,
      comment: '目标ID',
    },
    parent_id: {
      type: INTEGER,
      comment: '父评论ID（回复）',
    },
    content: {
      type: TEXT,
      allowNull: false,
      comment: '评论内容',
    },
    rating: {
      type: INTEGER,
      comment: '评分(1-5)',
    },
    like_count: {
      type: INTEGER,
      defaultValue: 0,
      comment: '点赞数',
    },
    reply_count: {
      type: INTEGER,
      defaultValue: 0,
      comment: '回复数',
    },
    is_deleted: {
      type: INTEGER,
      defaultValue: 0,
      comment: '是否删除(0:正常 1:用户删除 2:管理员删除)',
    },
    created_at: {
      type: DATE,
      allowNull: false,
      defaultValue: app.Sequelize.NOW,
    },
    updated_at: {
      type: DATE,
      allowNull: false,
      defaultValue: app.Sequelize.NOW,
    },
    deleted_at: {
      type: DATE,
      comment: '删除时间',
    },
  }, {
    tableName: 'comments',
    timestamps: true,
    paranoid: true,
    underscored: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    deletedAt: 'deleted_at',
    comment: '评论表',
  });

  // 关联关系
  Comment.associate = function() {
    // 属于用户
    app.model.Comment.belongsTo(app.model.User, {
      foreignKey: 'user_id',
      as: 'user',
    });

    // 父评论
    app.model.Comment.belongsTo(app.model.Comment, {
      foreignKey: 'parent_id',
      as: 'parent',
    });

    // 子评论
    app.model.Comment.hasMany(app.model.Comment, {
      foreignKey: 'parent_id',
      as: 'replies',
    });
  };

  return Comment;
};
